package com.chenju.invokechainservice.utils;

import com.chenju.invokechainservice.common.exceptions.FunnyException;
import com.chenju.invokechainservice.common.exceptions.FunnyFileNotFoundException;
import com.chenju.invokechainservice.common.exceptions.FunnyValidationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FunnyXmlUtils {
    public static Document loadXMLDocument(String XMLPath) throws FunnyValidationException{
        try {
            // 指定XML文件路径
            File xmlFile = new File(XMLPath);

            // 创建一个DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // 创建一个DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 使用DocumentBuilder解析XML文件，得到Document对象
            return builder.parse(xmlFile);
        } catch (ParserConfigurationException | IOException | SAXException e) {
            throw new FunnyValidationException(String.format("请检查XMLPath %s 是否正确，否则可能是XML格式有误导致解析出现了异常，请检查！", XMLPath));
        }
    }

    public static List<String> findValueByXPath(String XMLPath, String xPathExpression) throws FunnyValidationException{
        // 创建一个list对象来存储查找的节点
        List<String> results = new ArrayList<>();

        // 创建一个XPath对象
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();

        XPathExpression expression = null;
        try {
            expression = xPath.compile(xPathExpression);
            // 加载Document对象
            Document document = loadXMLDocument(XMLPath);
            // 通过XPath表达式获取标签的值
            NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

            for (int i=0; i<nodeList.getLength(); i++){
                results.add(nodeList.item(i).getTextContent());
            }

            return results;
        } catch (XPathExpressionException e) {
            throw new FunnyValidationException("XPath Expression不正确，请检查");
        }
    }

    public static void main(String[] args) {
        List<String> valueByXPath = findValueByXPath("D:\\Project\\springboot-easytest\\pom.xml", "/project/modules/module");
        System.out.println(valueByXPath);
    }
}
